﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AgencyEntityLib.BaseEntity;

public partial class Ctl_ctlPaymentsPlan : System.Web.UI.UserControl
{
    public Func<bool> OnSave;
    public Func<bool> OnRefresh;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public override void DataBind()
    {        
        myDataBind();
    }
    void myDataBind()
    {
        

        if(null== _ContractSupplier )
                return ;

        if (!(_ContractSupplier().ContractStatus is ContractStatus_Contract) )
                return;



        lvPayments.DataSource = (Payments ==null?null :Payments .GetPaymentsItems ()) ;
        lvPayments.DataBind();

        lvPaymentsPlan.DataSource = PaymentsPlan.ToArray <PaymentsPlanItem>() ;
        lvPaymentsPlan.DataBind();
        lblPlanSumma.DataBind();
        lblSumma.DataBind();
        Label3.DataBind();
        Label4.DataBind();
    }

    private PaymentsPlan PaymentsPlan
    { 
        get
            {
                if (!(_ContractSupplier().ContractStatus is ContractStatus_Contract))
                    return null;
                else
                    return (_ContractSupplier().ContractStatus as ContractStatus_Contract).PaymentsPlan;

        }
        
    }

    private Payments Payments
    {
        get
        {
            if (!(_ContractSupplier().ContractStatus is ContractStatus_Contract))
                return null;
            else
                return (_ContractSupplier().ContractStatus as ContractStatus_Contract).Payments ;

        }

    }

    /// <summary>
    /// Функция поставщик поверхностей контракта
    /// </summary>
    protected Func<Contract> _ContractSupplier;

    public Func<Contract> ContractSupplier { get { return _ContractSupplier; } set { _ContractSupplier = value; } }


    public string BtnAddFilter_ClientID { get { return btnClose.ClientID.Replace("_", "$"); } }

    public string GetContractDescribe()
    {
        return ContractSupplier().Number;
    }

    protected void btnRemovePayment_click(object sender, ImageClickEventArgs e)
    {
        if (null == OnSave)
            return;

        ImageButton btn = (ImageButton)sender;
        PaymentsPlan.Remove(btn.CommandArgument);
        OnSave();
        myDataBind();
    }

    protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
    {

        

        PaymentsPlanItem i = new PaymentsPlanItem() { Date = DateTime.Now, Summa = 0 };
        PaymentsPlan.Add(i);
        PaymentsPlan.Reset();

        if(OnSave())    
            lvPaymentsPlan.EditIndex = -1;

        myDataBind ();
        
    }

    
    /// <summary>
    /// Текущя задолженость 
    /// сумма по плану до ближайшего платежного дня вычесть 
    /// сумма платежей до текщего дня    
    /// </summary>
    /// <returns></returns>
    protected double GetCurrentRests()
    {
        return _ContractSupplier().GetCurrentRests();
    }

    protected double  GetRests()    
    {
          return _ContractSupplier().GetRests ();
    }

    protected double  GetPlanPaymentsSumma()
    {

        return _ContractSupplier().GetPlanPaymentsSumma();
    }

    protected double  GetPaymentsSumma()
    {
        return _ContractSupplier().GetPaymentsSumma ();
    }

    private Func<ListViewDataItem, bool> LvUpdCmd;

    /// <summary>
    /// вернуть сумму латежей на определенное число
    /// </summary>
    /// <param name="?"></param>
    protected  double  GetPaymentsForPeriod(object  DataItem)
    {
        
        if (0==Payments.Count )
                    return 0;
        
        PaymentsPlanItem i = (PaymentsPlanItem)DataItem;
        PaymentsPlanItem Prev_i =PaymentsPlan.GetPrev (i);


        double res = (_ContractSupplier().ContractStatus as ContractStatus_Contract).Payments.SummaForBetween(Prev_i.Date, i.Date);
        return res;

       // return 0;
    }

    private bool Updt_lvPayments(ListViewDataItem item)
    {
        HiddenField hf = (HiddenField)item.FindControl("hfID");
        TextBox t1 = (TextBox)item.FindControl("txtDate");
        TextBox t2 = (TextBox)item.FindControl("txtSumma");
        PaymentItem i = (PaymentItem)(_ContractSupplier().ContractStatus as ContractStatus_Contract).Payments [hf.Value];
        i.Date = Convert.ToDateTime(t1.Text);
        i.Summa = Convert.ToInt32(t2.Text);
        if (OnSave != null)
            OnSave();

        return true;
    }
    
    private bool  Updt_lvPaymentsPlan(ListViewDataItem item)
    {
        HiddenField hf = (HiddenField)item.FindControl("hfID");
        TextBox t1 = (TextBox)item.FindControl("txtDate");
        TextBox t2 = (TextBox)item.FindControl("txtSumma");
        PaymentsPlanItem i = (PaymentsPlanItem)PaymentsPlan[hf.Value];
        i.Date = Convert.ToDateTime(t1.Text);
        i.Summa = Convert.ToInt32 (t2.Text);
        //if (OnSave != null)
        //    OnSave();

        return true;
    }
    
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;
        ListView lv = (ListView)sender;

        if (lv .ID.Equals ("lvPayments"))
            LvUpdCmd = Updt_lvPayments;
        else
            LvUpdCmd = Updt_lvPaymentsPlan;

        switch (e.CommandName)
        {
            case "Edit":
                {
                      
                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;
                    break;
                }
            case "Insert":
                {
                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item)) 
                    lv.EditIndex = -1;    
                    break;
                }
            case "Delete":
                {

                    break;
                }
        }

        //switch (lv.ID)
        //{

        //    //case "lvSurfaceSet":
        //    //    lvSurfaceSet.DataSource  = ContractAsList;
        //    //    lvSurfaceSet.DataBind();                
        //    //    break;
        //    default:
        //        lv.DataSource = _ContractSupplier ().PaymentsPlan ;
        //        break;
        //}        
        myDataBind();
        
    }

    protected void ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    
    protected void ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }

    protected void btnRemovePayment_Click(object sender, ImageClickEventArgs e)
    {
        if (null == OnSave)
            return;

        ImageButton btn = (ImageButton)sender;
        (_ContractSupplier().ContractStatus as ContractStatus_Contract).Payments.Remove(btn.CommandArgument);
        OnSave();
        myDataBind();
    }
   
    protected void btnAddPayment0_Click(object sender, ImageClickEventArgs e)
    {        
        PaymentItem i = new PaymentItem() { Date = DateTime.Now, Summa = 0 };
        (_ContractSupplier().ContractStatus as ContractStatus_Contract ).Payments.Add(i);        

        if (OnSave())
            lvPaymentsPlan.EditIndex = -1;

        myDataBind();
    }
    
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (OnSave != null)
            OnSave();
    }
}
